package uk.ac.nott.cs.g53dia.bee;

import java.io.File;

import uk.ac.nott.cs.g53dia.Bee;
import utils.ControlPanel;
import utils.PropertiesHandler;
import utils.RandomGenerator;
import utils.Simulation;
import valueobj.SimulationSettings;

public class Main {

  public static void main(String... args) {
    String label = "MyBee";
    PropertiesHandler p = new PropertiesHandler();
    SimulationSettings settings = null;
    if (args.length > 2) {
      System.err.println("Maximum number of arguments is 2.");
      System.exit(1);
    }

    if (args.length == 2) {
      if (!new File(args[1]).exists()) {
        System.err.println("File with configuration does not exist.");
        System.exit(1);
      }
      settings = p.getSettings(args[1]);
    } else {
      settings = p.getSettings();
    }

    if (args.length >= 1) {
      try {
        settings.setBeeClass((Class<? extends Bee>) Class.forName("uk.ac.nott.cs.g53dia.bee." + args[0]));
      } catch (ClassNotFoundException e) {
        System.err.println("Class " + args[0] + " has not been found.");
        e.printStackTrace();
        System.exit(1);
      }
      label = args[0];
    }

    RandomGenerator.initialize(settings.getRandomSeed());
    Simulation.setSimulator(new BeeSimulator());
    ControlPanel.initialize(settings, label);
    ControlPanel cPanel = ControlPanel.getInstance();
    if (args.length < 2) {
      while (true) {
        synchronized (cPanel) {
          while (!Simulation.isStarted()) {
            try {
              cPanel.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        }

        Simulation.setSettings(cPanel.getSettings());
        Simulation.getSimulator().init();
        Simulation.getSimulator().simulate();
        // Simulation.getSimulator().results();
        Simulation.getSimulator().clean();
      }
    } else { // own config
      Simulation.setSettings(settings);
      Simulation.getSimulator().init();
      Simulation.setStarted(true);
      Simulation.getSimulator().simulate();
      Simulation.getSimulator().clean();
      System.exit(0);
    }
  }

}
